import 'package:flutter_admin/api/odoo/finished_in_scan_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/finish_in_scan.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qrscan/qrscan.dart' as scanner;

class FinishedInScanList extends StatefulWidget {
  FinishedInScanList({Key? key}) : super(key: key);

  @override
  _FinishedInScanState createState() => _FinishedInScanState();
}

class _FinishedInScanState extends State<FinishedInScanList> {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();

  FinishedInScan finishedInScan = FinishedInScan();
  List<FinishedInScan> selectedList = [];
  List tableList = [];
  var _subscription;
  @override
  void initState() {
    super.initState();
    // finishedInScan.productorderno = 'WH/MO/00012';
    // finishedInScan.productCode = 'FURN_6666';

    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "finishedIn")
        .listen(_onEnvent);
    WidgetsBinding.instance!.addPostFrameCallback((c) {});
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码获得的code
  void _onEnvent(dynamic obj) {
    try {
      var barcode = obj["scan"].toString();
      if (barcode.contains("|")) {
        finishedInScan.productorderno = barcode.split('|')[0];
        finishedInScan.productCode = barcode.split('|')[1];
        _loadData();
      }else{
        CryUtils.message("请扫描成品库产品二维码");
      }

    } catch (e) {
      print(e);
      // CryUtils.message(e.toString());
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '生产订单号',
            enable: false,
            value: finishedInScan.productorderno,
            onSaved: (v) {
              finishedInScan.productorderno = v;
            },
          ),
          CryInput(
            width: 280,
            label: '物料编号',
            enable: false,
            value: finishedInScan.productCode,
            onSaved: (v) {
              finishedInScan.productCode = v;
            },
          ),
        ],
      ),
    );
    var table = DataTable(
      columns: [
        DataColumn(label: Text('生产订单号')),
        DataColumn(label: Text("物料编号")),
        DataColumn(label: Text("物料名称")),
        DataColumn(label: Text("规格型号")),
        // DataColumn(label: Text("批次号")),
        DataColumn(label: Text("入库数量")),
        DataColumn(label: Text("计量单位")),
      ],
      rows: this.tableList.map((m) {
        FinishedInScan finishedInScan = FinishedInScan.fromMap(m);

        print(m);
        var result = DataRow(cells: [
          DataCell(Text(finishedInScan.productorderno ?? '--')),
          DataCell(Text(finishedInScan.productCode ?? '--')),
          DataCell(Text(finishedInScan.productName!)),
          DataCell(Text(finishedInScan.productstyle!)),
          // DataCell(Text(finishedInScan.batchno!)),
          DataCell(Text(finishedInScan.stockqty!)),
          DataCell(Text(finishedInScan.unitname!)),
        ]);
        return result;
      }).toList(),
    );

    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButton(
            label: "扫码",
            iconData: Icons.view_headline,
            onPressed: () => {_scan()}),
        // CryButton(
        //     label: "搜索",
        //     iconData: Icons.view_headline,
        //     onPressed: () => {_query()}),
      ],
    );
    var footerBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: "确定",
          onPressed: () {
            var domain = [];
            domain.add(['location_id', '=', tableList[0]["location_dest_id"][0]]);
            domain.add(['productorderno', '=', tableList[0]["productorderno"]]);
            this.tableList.forEach((element) {
              domain.add({
                'default_code':
                    element['product_tmpl_id']['default_code'].toString(),
                'num': element['product_qty']
              });
            });
            FinishedInScanOdooApi.saveOrUpdate(domain)
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                //CryUtils.message(re s.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
            // Navigator.pop(context);
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        title: Text("车间成品库扫码入库"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          form,
          // isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(
              child: SingleChildScrollView(
            child: SingleChildScrollView(
                scrollDirection: Axis.horizontal, child: table),
          )),
        ],
      ),
      bottomNavigationBar: footerBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
  }


  _loadData() async {
    print(finishedInScan.productorderno);
    var finishedInScanToOdoo = [
      if (finishedInScan.productorderno != null &&
          finishedInScan.productorderno != '')
        ['name', '=', finishedInScan.productorderno],
      if (finishedInScan.productCode != null &&
          finishedInScan.productCode != '')
        [
          'product_id.product_tmpl_id.default_code',
          '=',
          finishedInScan.productCode
        ],
    ];
    ResponseBodyApi responseBodyApi = await FinishedInScanOdooApi.page(
        data: {"domainList": finishedInScanToOdoo});
    if (responseBodyApi.success!) {
      tableList = responseBodyApi.data;
      setState(() {});
    }
  }

  Future _scan() async {
    await Permission.camera.request();
    String? barcode = await scanner.scan();
    finishedInScan.productorderno = barcode!.split('|')[0];
    finishedInScan.productCode = barcode.split('|')[1];
    _loadData();
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _scan();
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.qr_code_scanner_outlined),
            title: Text('扫码'),
          ),
        ),
      ],
    );
  }
}
